package com.cpo.controllers;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.cpo.domain.Person;
import com.cpo.domain.PersonDTO;
import com.cpo.interfaces.ICreditCardDao;
import com.cpo.interfaces.IPersonDao;
import com.sun.org.apache.xpath.internal.operations.Mod;

@Controller
public class MainController {

	protected static Logger logger = Logger.getLogger("service");
	
	@Autowired
	private IPersonDao persondao;
	
	@Autowired
	private ICreditCardDao creditCardDao;
	
	@RequestMapping(value="/list", method=RequestMethod.GET)
	public String getRecords(Model model){
		logger.debug("Received request to shoe Records page");
		
		List<Person> persons = persondao.getAll();
		List<PersonDTO> personsDTO = new ArrayList<PersonDTO>();
		for(Person person:persons){
			PersonDTO personDTO = new PersonDTO();
			personDTO.setId(person.getId());
			personDTO.setFirstName(person.getFirstName());
			personDTO.setLastName(person.getLastName());
			personDTO.setMoney(person.getMoney());
			personDTO.setCreditCards(creditCardDao.getAll(person.getId()));
			personsDTO.add(personDTO);
		}
		model.addAttribute("persons", personsDTO);
		return "records";
	}
	
	@RequestMapping(value="/add", method=RequestMethod.GET)
	public String getAdd(Model model){
		model.addAttribute("personAttribute",new Person());
		return "add_record";
	}
	
	@RequestMapping(value="/add", method=RequestMethod.POST)
	public String postAdd(@ModelAttribute("personAttribute")Person person){
		logger.debug("Received request to ad new record");
		persondao.add(person);
		return "redirect:list.do";
	}
	
	@RequestMapping(value="/delete", method=RequestMethod.GET)
	public String getdelete(@RequestParam("id")Integer personId){
		logger.debug("Received request to delete record");
		persondao.delete(personId);
		return "redirect:list.do";
	}
	
	@RequestMapping(value="/edit", method=RequestMethod.GET)
	public String getEdit(@RequestParam("id")Integer personId, Model model){
		Person existingPerson = persondao.get(personId);
		model.addAttribute("personAttribute",existingPerson);
		return "edit_record";
		
	}
	@RequestMapping(value="/edit", method=RequestMethod.POST)
	public String getPost(@RequestParam("id")Integer personId, @ModelAttribute("personAttribute")Person person){
		logger.debug("Received request to edit existing person");
		person.setId(personId);
		persondao.edit(person);
		return "redirect:list.do";
	}
}
